package com.dog.basics.common.util;


import cn.hutool.core.date.format.FastDateFormat;

import java.net.SocketException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生成流水号工具类
 *
 * @author fengjukang
 */
public class serialNumberUtils {

    /**
     * 生成流水号 17位时间戳 + 4 位机器号+ 3 位随机数
     *
     * @return
     * @throws SocketException
     * @author fengjukang
     */
    private final static char[] BASE_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    private final static AtomicInteger SEQ3 = new AtomicInteger(Integer.MAX_VALUE);

    public static StringBuilder serialNumberGenerate() throws SocketException {

        //生成的流水号
        StringBuilder serialNumber = new StringBuilder();
        //时间串
        serialNumber.append(FastDateFormat.getInstance("yyyyMMddHHmmssSSS").format(new Date()));

        //Mac地址
		/*Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
		while (networkInterfaces.hasMoreElements()) {
			NetworkInterface networkInterface = networkInterfaces.nextElement();
			if (null == networkInterface) {
				continue;
			}
			byte[] macBytes = networkInterface.getHardwareAddress();
			if (networkInterface.isUp() && !networkInterface.isLoopback() && null != macBytes && macBytes.length == 6) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0, nLen = macBytes.length; i < nLen; i++) {
					byte b = macBytes[i];
					sb.append(Integer.toHexString((b & 240) >> 4));
					sb.append(Integer.toHexString(b & 15));
					if (i < nLen - 1) {
						sb.append("-");
					}
				}
				int CRC16Code;
				String macAddress = sb.toString().toUpperCase();
				if (null == macAddress) {
					CRC16Code = 0;
				}
				byte[] data = macAddress.getBytes(Charset.forName("utf-8"));
				CRC16 crc16 = new CRC16();
				for (byte b : data) {
					crc16.update(b);
				}
				//serialNumber.append(String.valueOf(crc16.value).substring(0,4));
			}
		}*/
        //AtomicInteger随机数

        serialNumber.append(nextseq3());

        return serialNumber;
    }

    //AtomicInteger随机数
    public static String nextseq3() {
        int nextSequence = SEQ3.incrementAndGet();
        if (nextSequence >= 0) {
            nextSequence = Integer.MAX_VALUE - nextSequence;
        } else {
            nextSequence = Integer.MAX_VALUE + 1 + nextSequence;
        }
        int mod = nextSequence % (BASE_CHARS.length * BASE_CHARS.length * BASE_CHARS.length);
        int mod1 = nextSequence % (BASE_CHARS.length * BASE_CHARS.length);
        return BASE_CHARS[mod / (BASE_CHARS.length * BASE_CHARS.length)] + "" + BASE_CHARS[mod1 / BASE_CHARS.length] + "" + BASE_CHARS[mod1 % BASE_CHARS.length];
    }
}
